<template>
  <div class="bgc-default pad-20">
    <div class="bg-color-white pad-20">
      <div class="tabs-box mar-t--10">
        <el-tabs v-model="afterSale.afterSaleStatus" @tab-click="statusClick">
          <el-tab-pane :label="labels[0]" name="0"> </el-tab-pane>
          <el-tab-pane :label="labels[1]" name="1"> </el-tab-pane>
          <el-tab-pane :label="labels[2]" name="2"> </el-tab-pane>
          <el-tab-pane :label="labels[3]" name="3"> </el-tab-pane>
          <el-tab-pane :label="labels[-1]" name="-1"> </el-tab-pane>
          <el-tab-pane :label="labels[4]" name="4"> </el-tab-pane>
          <el-tab-pane :label="labels[100]" name="100"></el-tab-pane>
        </el-tabs>
      </div>

      <!--顶部搜索 -->
      <div class="top-operate-default flex-col" style="align-items: baseline; padding: 20px 0; height: 100%; ">
        <div class="search-item">
          <label>搜索订单：</label>
          <el-select v-model="afterSale.textCol" class="select-class">
            <el-option label="退货申请单号" value="afterSaleNo"></el-option>
            <el-option label="关联订单号" value="orderNo"></el-option>
            <el-option label="退货快递单号" value="trackingNo"></el-option>
            <el-option label="买家姓名" value="customerNickname"></el-option>
            <el-option label="买家手机号" value="customerPhone"></el-option>
          </el-select>
          <el-input v-model="afterSale.textValue" placeholder="请输入内容" style="width: 230px;"></el-input>
          <label class="mar-l-20">关联订单：</label>
          <el-select v-model="defaultQuery.deliveryMode" placeholder="关联订单类型" class="select-class">
            <el-option v-for="item in storeOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <label class="mar-l-20">时间筛选：</label>
          <el-select v-model="afterSale.timeCol" class="select-class">
            <el-option label="申请时间" value="createTime"></el-option>
            <el-option label="审核时间" value="auditTime"
              v-if="afterSale.afterSaleStatus > 0 || afterSale.afterSaleStatus == -1"></el-option>
            <el-option label="未同意时间" value="rejectTime"
              v-if="afterSale.afterSaleStatus > 3 || afterSale.afterSaleStatus == -1"></el-option>
            <el-option label="确认时间" value="refundGoodsTime" v-if="afterSale.afterSaleStatus > 1"></el-option>
            <el-option label="退款时间" value="refundMoneyTime" v-if="afterSale.afterSaleStatus > 2"></el-option>
            <el-option label="关闭时间" value="closeTime" v-if="afterSale.afterSaleStatus > 3"></el-option>
          </el-select>
          <el-date-picker v-model="afterSale.timeValue" type="daterange" range-separator="至"
            value-format="yyyy-MM-dd HH:mm:ss" :default-time="['00:00:00', '23:59:59']" start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
          <el-select v-if="afterSale.afterSaleStatus == 100" v-model="afterSaleStatus" placeholder="申请状态">
            <el-option label="全部" value=" "></el-option>
            <el-option v-for="(val, key) in dict.afterSaleStatus" :key="key" :label="val" :value="key" />
          </el-select>
        </div>
        <div class="search-item mar-t-10">
          <label>申请类型：</label>
          <el-select v-model="afterSale.afterSaleType" placeholder="申请类型" class="select-class">
            <el-option label="全部" value=""></el-option>
            <el-option v-for="(val, key) in dict.afterSaleType" :key="key" :label="val" :value="key" />
          </el-select>
          <label class="mar-l-20">退货原因：</label>
          <el-select v-model="afterSale.afterSaleReasonId" placeholder="退货原因" class="select-class">
            <el-option label="全部" value=""></el-option>
            <el-option v-for="item in afterSaleReasonList" :key="item.reasonId" :label="item.cancelReason"
              :value="item.reasonId"></el-option>
          </el-select>
        </div>
        <div class="search-item mar-t-10">
          <el-button-group class="mar-l-60">
            <el-button type="primary" @click="handleSearch" style="margin-left: 10px">查询</el-button>
            <el-button plain="" @click="resetSearch">重置</el-button>
          </el-button-group>
        </div>
      </div>
      <!-- 全选、操作 -->
      <div>
        <div class="pad-t-15 pad-b-15 font-14 v-align-c">
          <el-checkbox class="mar-l-14 mar-r-0" v-model="checkedAll" @change="checkedAllHandle"><span
              class="mar-l-20">当页全选</span></el-checkbox>
          <span class="pad-l-4 pad-r-4">|</span>
          <div class="width-80">已选{{checkList.length}}项</div>
          <el-button class="batch-btn" @click="exportData">批量导出</el-button>
        </div>
      </div>
      <!-- 内容列表 -->
      <div class="tab-container">
        <div class="c-table">
          <div class="c-table__head">
            <div class="c-table__td select">
              <el-checkbox v-model="checkedAll" @change="checkedAllHandle" />
            </div>
            <div class="c-table__td goods-info">退货商品</div>
            <div class="c-table__td">买家信息</div>
            <div class="c-table__td">退货原因</div>
            <div class="c-table__td">审核方</div>
            <div class="c-table__td">退款金额</div>
            <div class="c-table__td">{{timeDict[afterSale.afterSaleStatus][0]}}时间</div>
          </div>
          <div class="c-table__body">
            <div class="c-table__row" v-for="(item, index) in afterSaleList" :key="index">
              <div class="c-row__head">
                <div class="goods-type" v-if="item.deliveryType !== 3" :class="{'goods-type-2': item.orderType === 31}">
                  {{item.orderType === 31 ? '批发' : '门店'}}
                </div>
                <div class="goods-type" v-if="item.deliveryType === 3">团购</div>
                <div>申请单号：<span>{{item.afterSaleNo}}</span></div>
                <template v-if="item.orderNo">
                  <div class="mar-l-20" @click="goOrderDetail(item.orderId)">关联单号：<span
                      style="color: #409eff;cursor:pointer;">{{item.orderNo}}</span></div>
                  <div class="mar-l-20" v-if="item.projectOrder">[{{dict.orderStatus[item.projectOrder.orderStatus]}}]
                  </div>
                </template>
              </div>
              <div class="c-table__tr" v-for="(goods, trIndex) in item.goodsList" :key="trIndex">
                <div class="c-table__td select">
                  <el-checkbox v-model="item.checked" @change="checkedHandle" />
                </div>
                <div class="c-table__td v-align-c goods-info" @click="showDetail(item)">
                  <img :src="goods.goodsImageUrl" alt="" class="width-65 height-65">
                  <div class="line-2 mar-l-10 flex-item" style="color: #155bd4;">{{goods.goodsTitle}}</div>
                </div>
                <div class="c-table__td">
                  <div>{{item.customerNickname}}</div>
                  <div>{{item.customerPhone}}</div>
                </div>
                <div class="c-table__td">
                  {{ afterSaleReasonMap[item.afterSaleReasonId] ? afterSaleReasonMap[item.afterSaleReasonId].cancelReason : '' }}
                </div>
                <div class="c-table__td">门店</div>
                <div class="c-table__td">
                  <div v-if="item.refundAmount">￥{{item.refundAmount ? item.refundAmount : '0.00'}}</div>
                </div>
                <div class="c-table__td">{{item[timeDict[item.afterSaleStatus][1]]}}</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="searchListQuery.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="searchListQuery.size"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>


<script>
  import {
    pageAfterSale,
    statAfterSale
  } from '@/api/after-sale/after-sale'
  import {
    listAfterSaleReason
  } from '@/api/after-sale/after-sale-reason'
  import {
    getDictByGroupName,
    downloadFile
  } from '@/api/common/common'
  import CustomTable from '../components/CustomTable/index'

  export default {
    components: {
      CustomTable
    },
    data() {
      return {
        storeOptions: [{
          value: 'allDeliveryModel',
          label: '全部'
        }, {
          value: 'storeOrder',
          label: '门店订单'
        }, {
          value: 'communityGroupExtraction',
          label: '社区团购'
        }],
        total: 0,
        multipleSelection: [],
        listLoading: true,
        searchListQuery: {},
        defaultQuery: {
          enterpriseId: this.getEnterpriseId(),
          orderType: '30',
          afterSaleType: '',
          afterSaleReasonId: '',
          deliveryTypeList: '3, 4, 5',
          deliveryMode: 'allDeliveryModel',
          currentPage: 1,
          size: 10
        },
        afterSale: {
          afterSaleStatus: '0',
          timeCol: 'createTime',
          timeValue: [],
          textCol: 'afterSaleNo',
          textValue: '',
          isNotice: false,
          afterSaleReasonId: '',
          afterSaleType: '',
          orderType: '30'
        },
        dict: {
          orderStatus: {}
        },
        afterSaleList: [],
        afterSaleReasonList: [],
        afterSaleReasonMap: {},
        labels: {
          '0': '待审核(0)',
          '1': '待退货(0)',
          '2': '退款中(0)',
          '3': '已完成(0)',
          '-1': '未同意(0)',
          '4': '已关闭(0)',
          '100': '全部(0)'
        },
        orderTimeCol: 'createTime',
        orderTimeCols: {
          '0': 'createTime'
        },
        timeDict: {
          '0': ['申请', 'createTime'],
          '1': ['审核', 'auditTime'],
          '2': ['审核', 'auditTime'],
          '3': ['退款', 'refundMoneyTime'],
          '-1': ['未同意', 'rejectTime'],
          '4': ['关闭', 'closeTime'],
          '-2': ['关闭', 'rejectTime'],
          '-3': ['关闭', 'rejectTime'],
          '100': ['']
        },
        afterSaleStatus: '',
        allChecked: false,
        checkedAll: false,
        checkList: []
      }
    },
    filters: {
      dateFilter(e) {
        return e
      }
    },
    // 初始化页面
    created() {
      getDictByGroupName('ProjectOrderDTO').then(response => {
        Object.assign(this.dict, response.data)
      })
      this.searchListQuery = {
        ...this.defaultQuery
      }
      const afterSaleStatus = this.getCurrentPage().query.afterSaleStatus
      if (afterSaleStatus) {
        this.afterSale.afterSaleStatus = afterSaleStatus
      }
      this.init()
    },
    mounted() {},
    methods: {
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.init()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.init()
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
        if (this.multipleSelection.length === this.afterSaleList.length) {
          this.allChecked = true
        } else {
          this.allChecked = false
        }
      },
      setSearchListQuery() {
        // 搜索状态
        const currentPage = this.searchListQuery.currentPage
        const size = this.searchListQuery.size
        this.searchListQuery = {
          ...this.defaultQuery
        }
        this.searchListQuery.enterpriseId = this.getEnterpriseId()
        this.searchListQuery.currentPage = currentPage
        this.searchListQuery.page = currentPage
        this.searchListQuery.size = size
        switch (this.afterSale.afterSaleStatus * 1) {
          default:
            this.searchListQuery.afterSaleStatusList = ''
            this.searchListQuery.afterSaleStatus = this.afterSale.afterSaleStatus
            break
          case 4:
            this.searchListQuery.afterSaleStatus = ''
            this.searchListQuery.afterSaleStatusList = '-3,-2,4'
            break
          case 100:
            this.searchListQuery.afterSaleStatus = ''
            // 全部订单下再进行状态过滤
            if (this.afterSaleStatus || this.afterSaleStatus * 1 === 0) {
              this.searchListQuery.afterSaleStatus = this.afterSaleStatus
              this.searchListQuery.afterSaleStatusList = ''
            }
            if (this.afterSaleStatus * 1 === 4) {
              this.searchListQuery.afterSaleStatus = ''
              this.searchListQuery.afterSaleStatusList = '-3,-2,4'
            }
            break
        }
        this.searchListQuery.dateColumn = this.afterSale.timeCol
        this.searchListQuery.startDate = (this.afterSale.timeValue && this.afterSale.timeValue.length > 0) ? this
          .afterSale.timeValue[0] : ''
        this.searchListQuery.endDate = (this.afterSale.timeValue && this.afterSale.timeValue.length > 1) ? this
          .afterSale.timeValue[1] : ''
        this.searchListQuery[this.afterSale.textCol] = this.afterSale.textValue
        this.searchListQuery.afterSaleType = this.afterSale.afterSaleType
        this.searchListQuery.orderType = this.afterSale.orderType
        this.searchListQuery.afterSaleReasonId = this.afterSale.afterSaleReasonId
        this.orderTimeCol = this.orderTimeCols[this.searchListQuery.afterSaleStatus + '']
        if (!this.orderTimeCol) {
          this.orderTimeCol = 'createTime'
        }
        this.searchListQuery.supplierId = this.getSupplierId()
        this.searchListQuery.warehouseId = this.getWarehouseId()
      },
      init() {
        this.setSearchListQuery()
        statAfterSale({
          enterpriseId: this.getEnterpriseId(),
          supplierId: this.getSupplierId(),
          warehouseId: this.getWarehouseId(),
          memberId: this.getMemberId(),
          deliveryTypeList: '3, 4, 5'
        }).then(response => {
          if (response.isError) return
          this.labels[0] = '待审核(' + response.data[0] + ')'
          this.labels[1] = '待退货(' + response.data[1] + ')'
          this.labels[2] = '退款中(' + response.data[2] + ')'
          this.labels[3] = '已完成(' + response.data[3] + ')'
          this.labels[-1] = '未同意(' + response.data[-1] + ')'
          this.labels[4] = '已关闭(' + response.data[4] + ')'
          this.labels[100] = '全部(' + response.data[100] + ')'
        })

        this.searchListQuery.deliveryTypeList = ''
        this.searchListQuery.memberId = this.getMemberId()
        if (this.searchListQuery.deliveryMode === 'allDeliveryModel') {
          this.searchListQuery.deliveryTypeList = '3, 4, 5'
        } else if (this.searchListQuery.deliveryMode === 'storeOrder') {
          this.searchListQuery.deliveryTypeList = '4, 5'
        } else if (this.searchListQuery.deliveryMode === 'communityGroupExtraction') {
          this.searchListQuery.deliveryTypeList = '3'
        }
        pageAfterSale(this.searchListQuery).then(response => {
          if (response.isError) return
          this.total = response.data.total
          response.data.records.forEach(item => {
            item.checked = false
          })
          this.checkList = []
          this.checkedAll = false
          this.afterSaleList = this.$utils.deepClone(response.data.records)
          console.log('退货订单列表:', this.checkList)
          Object.assign(this.dict, response.data.dict)
          this.listLoading = false
        })
        listAfterSaleReason({
          enterpriseId: this.getEnterpriseId()
        }).then(response => {
          if (response.isError) return
          this.afterSaleReasonList = response.data
          this.afterSaleReasonList.forEach(reason => {
            this.afterSaleReasonMap[reason.reasonId] = reason
          })
        })
      },
      statusClick() {
        this.searchListQuery.currentPage = 1
        this.init()
      },
      goOrderDetail(orderId) {
        if (this.getWarehouseId()) {
          this.$router.push({
            path: '/delivery/order/detail/index',
            query: {
              orderId: orderId
            }
          })
        } else {
          this.$router.push({
            path: '/order/store/detail/index',
            query: {
              orderId: orderId
            }
          })
        }
      },
      handleSearch() {
        this.searchListQuery.currentPage = 1
        this.init()
      },
      resetSearch() {
        this.searchListQuery = {
          ...this.defaultQuery
        }
        this.afterSale = {
          timeCol: 'createTime',
          timeValue: [],
          textCol: 'afterSaleNo',
          textValue: '',
          orderType: '30',
          afterSaleType: '',
          afterSaleReasonId: '',
          afterSaleStatus: '0'
        }
        this.init()
      },
      exportData() {
        if (this.checkList.length > 0) {
          const afterSaleIds = this.checkList.map(item => item.afterSaleId)
          downloadFile('/order/afterSale/exportData', {
            enterpriseId: this.getEnterpriseId(),
            afterSaleIds: afterSaleIds.join(',')
          }, '售后单.xlsx')
        } else {
          this.setSearchListQuery()
          downloadFile('/order/afterSale/exportData', this.searchListQuery, '售后单.xlsx')
        }
      },
      selectAll() {
        if (this.multipleSelection.length === 0 || this.multipleSelection.length < this.afterSaleList.length) {
          this.afterSaleList.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          })
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      },
      checkedAllHandle(val) {
        if (val) {
          this.afterSaleList.forEach(item => {
            item.checked = true
          })
          this.checkList = this.$utils.deepClone(this.afterSaleList)
        } else {
          this.afterSaleList.forEach(item => {
            item.checked = false
          })
          this.checkList = []
        }
      },
      checkedHandle(val) {
        const isAll = this.afterSaleList.findIndex(item => {
          return item.checked === false
        })
        if (isAll === -1) {
          this.checkedAll = true
          this.checkList = this.$utils.deepClone(this.afterSaleList)
        } else {
          this.checkedAll = false
          const list = this.afterSaleList.filter(item => item.checked === true)
          this.checkList = list
        }
      }
    }
  }
</script>


<style lang="less" scoped>
  .tips {
    height: 45px;
    line-height: 45px;
    font-size: 14px;
    background-color: #fff7cc;
    color: #333333;
    padding-left: 20px;
  }

  .align-h-l {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: space-evenly;
  }

  .mar-l-60 {
    margin-left: 60px;
  }

  .search-item {
    /deep/.el-input {
      width: 200px;
    }
  }

  .select-class {
    /deep/.el-input {
      width: 140px;
    }
  }

  .c-table {
    overflow: auto;

    .c-table__td {
      width: 215px;
      padding: 0 15px;
      flex-shrink: 0;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }

    .c-table__head {
      width: fit-content;
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 50px;
      background: #f7f8fa;
      color: #333333;

      .goods-info {
        width: 300px;
      }

      .select {
        width: 50px;
      }

    }

    .c-table__body {
      width: fit-content;

      .c-table__row {
        .c-row__head {
          display: flex;
          align-items: center;
          justify-content: left;
          height: 50px;
          background-color: #f7f8fa;
          margin-top: 15px;
          border-top: 1px solid #edeff6;
          border-bottom: 1px solid #edeff6;
          position: relative;
          padding-left: 49px;

          .goods-type {
            position: absolute;
            left: 0;
            top: -1px;
            height: 25px;
            width: 39px;
            border-bottom-right-radius: 28px;
            background-color: #ffe100;
            line-height: 25px;
            font-size: 12px;
            box-sizing: border-box;
            padding-left: 4px;
          }

          .goods-type-2 {
            background-color: #ff7024;
            color: white;
          }
        }

        .c-table__tr {
          display: flex;
          align-items: center;
          justify-content: space-between;
          border-bottom: 1px solid #edeff6;
          height: 95px;

          &:hover {
            background-color: #f7f8fa;
            cursor: pointer;

            .text-align-r {
              background-color: #f7f8fa;
            }
          }

          &:first-child {
            &:hover {
              background-color: unset;
            }
          }

          .goods-info {
            width: 300px;
          }

          .select {
            width: 50px;
          }
        }
      }
    }
  }

  // 2行文字展示
  .line-2 {
    line-height: 1.4;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    word-break: break-word;
  }

  .text-align-r {
    justify-content: flex-end !important;
    position: sticky;
    position: -webkit-sticky;
    right: 0;
    top: 0;
    background-color: white;
  }

  .c-table__head {
    .text-align-r {
      background-color: #f7f8fa;
    }
  }
</style>
